
<template>
  <div
    class="add-user"
    ref="course-wrap"
    :style="{ height: wrapHeight + 'px' }"
  >
    <el-button
      class="btn-back"
      type="custom"
      size="small"
      @click="handleBack"
      plain
      >返回列表</el-button
    >
    <div
      id="userEdit"
      v-loading="loading"
      :style="{ height: wrapHeight - 80 + 'px' }"
    >
      <el-form ref="temp" :model="temp" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="账号" prop="account">
              <el-input
                v-model="temp.account"
                placeholder="请输入登录账号，推荐使用邮箱或手机号注册账号"
                :disabled="!addOrEdit"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input
                v-model="temp.userName"
                autocomplete="off"
                placeholder="请输入用户名"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="likeName">
              <el-input
                v-model="temp.likeName"
                placeholder="请输入昵称"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="addOrEdit">
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="temp.password"
                show-password
                autocomplete="new-password"
                :placeholder="passwordTips"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="addOrEdit">
            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input
                v-model="temp.confirmPassword"
                show-password
                :placeholder="passwordTips2"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <template>
                <el-radio v-model="temp.sex" label="1">男</el-radio>
                <el-radio v-model="temp.sex" label="2">女</el-radio>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件类型" prop="idType">
              <template>
                <el-radio v-model="temp.idType" label="1">身份证</el-radio>
                <el-radio v-model="temp.idType" label="2">其他</el-radio>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="false">
            <el-form-item label="用户类型" prop="type">
              <el-select
                style="width: 100%"
                v-model="temp.type"
                placeholder="请选择用户类型"
              >
                <el-option
                  v-for="(v, i) in typeData"
                  :key="i"
                  :label="v.label"
                  :value="v.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择部门" class="top_unit" prop="deptId">
              <el-popover
                placement="bottom-start"
                v-model="treeFlag"
                class="orgTree"
                trigger="click"
              >
                <el-tree
                  :data="companyTableData"
                  :props="defaultProps"
                  :expand-on-click-node="false"
                  node-key="id"
                  style="width: 400px"
                  @node-click="handleNodeClickDep"
                ></el-tree>
                <el-input
                  slot="reference"
                  ref="input"
                  v-model="treeName"
                  clearable
                  :readonly="true"
                  style="width: 100%"
                  placeholder="请选择部门"
                ></el-input>
              </el-popover>
              <i
                @click.stop="closeName"
                class="el-icon-circle-close"
                v-if="treeName"
              ></i>
              <i class="el-icon-arrow-down" v-else></i>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件号码" prop="idNumber">
              <template>
                <el-input
                  v-model="temp.idNumber"
                  type="number"
                  placeholder="请输入证件号码"
                ></el-input>
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="选择角色" prop="roleIds">
              <el-select
                style="width: 100%"
                v-model="temp.roleIds"
                multiple
                filterable
                collapse-tags
                placeholder="请选择角色"
              >
                <el-option
                  v-for="(v, i) in roleTableData"
                  :key="i"
                  :label="v.key"
                  :value="v.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学历" prop="education">
              <el-select
                v-model="temp.education"
                filterable
                placeholder="请选择学历"
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话">
              <el-input
                v-model="temp.phone"
                placeholder="请输入电话"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="职务" prop="duty">
              <el-input v-model="temp.duty" placeholder="请输入职务"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="false">
            <el-form-item label="校园卡号" prop="schoolCard">
              <el-input
                v-model="temp.schoolCard"
                type="number"
                placeholder="请输入校园卡号"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="衔级" prop="rank">
              <el-input v-model="temp.rank" placeholder="请输入衔级"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职称" prop="jobTitle">
              <el-input
                v-model="temp.jobTitle"
                placeholder="请输入职称"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="资源权限" prop="level">
              <el-select
                v-model="temp.level"
                filterable
                placeholder="请选择资源权限"
              >
                <el-option
                  v-for="item in levelData"
                  :key="item.value"
                  :label="item.deName"
                  :value="item.deValue"
                >
                  <span style="float: left">{{ item.deName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 12px">{{
                    item.content
                  }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="简介" prop="content">
              <UEditor
                ref="ueditor"
                :ueWidth="ueWidth"
                :defaultMsg="temp.content"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="btn-submit">
      <el-button type="custom" v-preventReClick @click="submitForm('temp')">
        提 交
      </el-button>
    </div>
  </div>
</template>

<script>
import {
  tbUserAdd,
  tbUserUpdate,
  tbUserVali,
  tbUserQueryOne,
} from '@/api/admin/user/user-manage.js'
import { tbRoleQuery } from '@/api/admin/system/role.js'
import { tbDeptQuery } from '@/api/admin/user/department-manage.js'
import { tbDictDefinitionQueryEnumList } from '@/api/admin/system/dictionary'
export default {
  data() {
    // 重复密码验证
    const pwdAgainCheck = async (rule, value, callback) => {
      //这样才能在回调里通过箭头函数获取到this对象
      if (value != this.temp.password) {
        callback(new Error('与密码不一致'))
      } else {
        //校验通过
        callback()
      }
    }
    return {
      temp: {
        isLeader: '1',
        idType: '1',
        level: '1',
        sex: '1',
        deptId: '',
        type: '',
        roleIds: [],
      },
      dstemp: { diskSpace: '50' },
      checkList: [],
      roleTableData: [],
      roleList: [],
      levelData: [],
      typeData: [],
      fileList: [],
      delData: [
        { value: '1', label: '可用' },
        { value: '2', label: '不可用' },
      ],
      configRoleList: [],
      configDeptList: [],
      isReduce: true,
      isSelect: false,
      addOrEdit: true,
      radio: '1',
      jurisdictionType: '1',
      userPassword: '',
      listQuery: {
        page: 1,
        limit: 10,
        userName: '',
        education: '',
        account: '',
        del: '',
      },
      defaultProps: {
        children: 'childList',
        label: 'name',
      },
      userTableData: [],
      companyTableData: [],
      dialogVisible: false,
      dialogFormVisible: false,
      roleConfigVisible: false,
      deptConfigVisible: false,
      fileUploadVisible: false,
      pageObj: {},
      treeFlag: false,
      treeFlag1: false,
      treeFlag2: false,
      treeName: '',
      treeName1: '',
      treeName2: '',
      deptIds: '',
      passwordTips: '请输入密码',
      passwordTips2: '请输入确认密码',
      fileTemp: '',
      dialogFormDiskSizeVisible: false, //设置磁盘空间大小弹出框
      options: [
        {
          value: '1',
          label: '博士',
        },
        {
          value: '2',
          label: '硕士',
        },
        {
          value: '3',
          label: '本科',
        },
        {
          value: '4',
          label: '大专',
        },
        {
          value: '5',
          label: '高中',
        },
      ],
      rules: {
        account: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          {
            min: 2,
            max: 30,
            message: '请输入2~30个字符',
            trigger: 'blur',
          },
        ],
        userName: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 2,
            max: 8,
            message: '请输入2~8位汉字、字母或数字',
            trigger: 'blur',
          },
        ],
        password: [
          {
            required: true,
            message: '请输入6~16个字符',
            trigger: 'blur',
            min: 6,
            max: 16,
          },
          {
            validator: function (rule, value, callback) {
              //校验中文的正则：/^[\u4e00-\u9fa5]{0,}$/
              if ((value + '').length < 6) {
                callback(new Error('请输入6~16个字符'))
              } else {
                //校验通过
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
        confirmPassword: [
          {
            required: true,
            message: '请输入确认密码',
            trigger: 'blur',
          },
          {
            validator: pwdAgainCheck,
            trigger: 'blur',
          },
        ],
        phone: [
          {
            required: true,
            message: '请输入联系电话',
            trigger: 'blur',
          },
          {
            type: 'number',
            validator: function (rule, value, callback) {
              if (/^1[345789]\d{9}$/.test(value) == false) {
                callback(new Error('请输入11位手机号'))
              } else {
                //校验通过
                callback()
              }
            },
            message: '请输入11位有效手机号码',
            trigger: ['blur', 'change'],
          },
        ],
        type: [
          {
            required: true,
            message: '请选择用户类型',
            trigger: ['blur', 'change'],
          },
        ],
        deptId: [
          {
            required: true,
            message: '请选择部门',
            trigger: ['blur', 'change'],
          },
        ],
        roleIds: [
          {
            required: true,
            message: '请选择用户角色',
            trigger: ['blur', 'change'],
          },
        ],
        level: [
          {
            required: true,
            message: '请选择资源权限',
            trigger: ['blur', 'change'],
          },
        ],
      },
      wrapHeight: 500,
      // userId: this.$route.params.id,
      // editType: this.$route.params.type,
      userId: this.$route.query.id,
      editType: this.$route.query.type,
      loading: false,
    }
  },
  computed: {
    ueWidth() {
      return this.$store.getters.windowWidth > 1400 ? 820 : 700
    },
  },
  watch: {
    //监测浏览器宽度对按钮做出改变
    width(val) {
      if (!this.timer) {
        this.width = val
        this.timer = true
        let _this = this
        setTimeout(function () {
          _this.timer = false
        }, 500)
      }
      // 这里可以添加修改时的方法
      if (val < 1812) {
        this.isReduce = false
      } else {
        this.isReduce = true
      }
    },
    addOrEdit: {
      immediate: true,
      handler(val) {
        this.$route.meta.title = val ? '新增用户' : '编辑用户'
      },
    },
  },
  mounted() {
    setTimeout(() => {
      this.init()
    }, 50)
    // this.queryUserLevel()
    this.queryUserType()
    this.getRoleList()
    this.getDeptList()
    this.getUserData()
  },
  methods: {
    init() {
      let wHeight = document.body.clientHeight
      let topDistance = this.$refs['course-wrap'].getBoundingClientRect().top
      this.wrapHeight = wHeight - topDistance - 42
    },
    getUserData() {
      if (!this.userId) return
      this.loading = true
      let row = {}
      if (this.editType == 'add') {
        this.addOrEdit = true
        this.temp.idType = '1'
        this.temp.sex = '1'
        this.treeName = ''
        this.loading = false
        return false
      } else {
        tbUserQueryOne(this.userId).then((res) => {
          row = res.data.data[0]
          this.addOrEdit = false
          let obj = { ...row }
          let roleArr = []
          for (let menuObj of obj.menuRoleList) {
            roleArr.push(menuObj.id)
          }
          for (let powerObj of obj.powerRoleList) {
            roleArr.push(powerObj.id)
          }
          obj.roleIds = roleArr
          this.temp = obj
          this.treeName = row.deptName
          this.loading = false
        })
      }
    },
    // 清空单位
    closeName() {
      this.treeName = ''
      this.temp.deptId = ''
    },
    // 选中上一级单位
    handleNodeClickDep(val) {
      this.treeName = val.name
      this.treeFlag = false
      this.temp.deptId = val.id
    },
    //查询用户等级
    async queryUserLevel() {
      let res = await this.$store.dispatch(
        'queryOpenApiTbDictDetailByCode',
        'TB_SYS_USER_LEVEL',
      )
      this.levelData = res
    },
    //查询用户类型
    queryUserType() {
      tbDictDefinitionQueryEnumList({ code: 'TB_SYS_USER_TYPE' }).then(
        (res) => {
          let arr = []
          for (let obj of res.data.data) {
            let list = {}
            list['label'] = obj.msg
            list['value'] = obj.value
            arr.push(list)
          }
          this.typeData = arr
        },
      )
    },
    //查询所有角色
    getRoleList() {
      //{type:this.jurisdictionType}只查询菜单角色
      let data = { type: 1, page: 1, limit: 999 }
      let userType = this.$store.state.userInfo.userInfo.menuRoleList.map(
        (v) => v.userType,
      )
      userType = Math.min(...userType)
      tbRoleQuery(data).then((res) => {
        let arr = []
        this.roleList = res.data.data
        for (let role of res.data.data) {
          if (role.userType >= userType) {
            let list = {}
            //这里需要的是id
            list['key'] = role.name
            list['value'] = role.id
            arr.push(list)
          }
        }
        this.roleTableData = arr
      })
    },
    //查询部门
    getDeptList() {
      tbDeptQuery({ pId: '0' }).then((res) => {
        this.companyTableData = res.data.data
      })
    },
    // 提交
    submitForm(form) {
      this.temp.content = this.$refs.ueditor.message
      this.temp.type = 40
      let { roleIds } = this.temp
      let res = this.roleList
        .filter((v) => roleIds.includes(v.id))
        .map((v) => parseInt(v.userType))
      if (res.length > 0) {
        this.temp.type = Math.min(...res)
      }
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.addOrEdit ? this.VerifyAccountNumber() : this.handleUpdate()
        }
      })
    },
    //验证账号是否存在
    VerifyAccountNumber() {
      tbUserVali({ account: this.temp.account, id: this.temp.id }).then(
        (res) => {
          if (res.data.msg === '0') {
            this.handleAdd('temp')
          } else {
            this.$message({
              message: '账号已存在',
              type: 'error',
            })
          }
        },
      )
    },
    //新增
    handleAdd() {
      this.$delete(this.temp, 'confirmPassword')
      tbUserAdd(this.temp).then((res) => {
        if (res.data.code === '0') {
          this.$message({
            message: '添加成功',
            type: 'success',
          })
          this.$router.push({ name: 'user-manage' })
        }
      })
    },
    //修改
    handleUpdate() {
      tbUserUpdate(this.temp).then((res) => {
        if (res.data.code === '0') {
          this.$message({
            message: res.data.msg,
            type: 'success',
          })
          this.$router.push({ name: 'user-manage' })
        }
      })
    },
    handleBack() {
      this.$router.go(-1)
    },
  },
}
</script>

<style lang="scss" scoped>
.add-user {
  position: relative;
  .btn-back {
    position: absolute;
    right: 0;
    top: -53px;
    z-index: 1;
  }
  .btn-submit {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    padding: 10px 0;
    background: #fff;
    border-top: 1px solid #ddd;
    z-index: 999;
    button {
      margin-left: 100px;
    }
  }
}
#userEdit {
  position: relative;
  background-color: #fff;
  overflow: auto;
  padding-top: 20px;
  .el-form-item.top_unit i.el-icon-circle-close,
  .el-form-item.top_unit i.el-icon-arrow-down {
    position: absolute;
    right: 10px;
    top: 13px;
    cursor: pointer;
    color: #c0c4cc;
  }

  form.el-form {
    width: 800px;
  }
  .el-select {
    width: 100%;
  }
}
</style>